package com.etonedu.meals.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.etonedu.meals.R;
import com.etonedu.meals.utils.Utils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/3/30.
 */
public class InternetDialog extends Dialog {

    public InternetDialog(Context context) {
        super(context);
    }

    public InternetDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    private final static int FIFTEEM = 1000;
    private final static int SECOND = 20;
    private static int FIFTEEM_SECOND = SECOND;
    private Timer fifteemTimer;

    private static TextView txt_close;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FIFTEEM:
                    FIFTEEM_SECOND --;
                    txt_close.setText(FIFTEEM_SECOND + "");
                    if (FIFTEEM_SECOND == 0) {
                        dismiss();
                    }
                    break;
            }
        }
    };

    public static class Builder {
        private Context context;
        private String title;
        private String url;
        private String positiveButtonText;
        private String negativeButtonText;
        private View contentView;
        private OnClickListener positiveButtonClickListener;
        private OnClickListener negativeButtonClickListener;
        private OnClickListener btnCloseListener;

        public Builder(Context context) {
            this.context = context;
        }

        /**
         * Set the Dialog title from resource
         *
         * @param title
         * @return
         */
        public Builder setTitle(int title) {
            this.title = (String) context.getText(title);
            return this;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getUrl() {
            return this.url;
        }

        /**
         * Set the Dialog title from String
         *
         * @param title
         * @return
         */

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public Builder setContentView(View v) {
            this.contentView = v;
            return this;
        }

        /**
         * Set the positive button resource and it's listener
         *
         * @param positiveButtonText
         * @return
         */
        public Builder setPositiveButton(int positiveButtonText,
                                         OnClickListener listener) {
            this.positiveButtonText = (String) context
                    .getText(positiveButtonText);
            this.positiveButtonClickListener = listener;
            return this;
        }

        public Builder setPositiveButton(String positiveButtonText,
                                         OnClickListener listener) {
            this.positiveButtonText = positiveButtonText;
            this.positiveButtonClickListener = listener;
            return this;
        }

        public Builder setBtnClose(OnClickListener listener) {
            this.btnCloseListener = listener;
            return this;
        }

        public Builder setNegativeButton(int negativeButtonText,
                                         OnClickListener listener) {
            this.negativeButtonText = (String) context
                    .getText(negativeButtonText);
            this.negativeButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(String negativeButtonText,
                                         OnClickListener listener) {
            this.negativeButtonText = negativeButtonText;
            this.negativeButtonClickListener = listener;
            return this;
        }

        public InternetDialog create() {

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // instantiate the dialog with the custom Theme
            final InternetDialog dialog = new InternetDialog(context, R.style.CustomDialog);
            final View layout = inflater.inflate(R.layout.layout_internet, null);
            dialog.addContentView(layout, new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
            // set the dialog title
            ((TextView) layout.findViewById(R.id.title)).setText(title);
            TextView imageView = (TextView) layout.findViewById(R.id.btn_close);
            TextView txt_version = (TextView) layout.findViewById(R.id.txt_version);
            txt_close = (TextView) layout.findViewById(R.id.txt_close);
            txt_version.setText(Utils.getVersion(context));

            final EditText edit = ((EditText)layout.findViewById(R.id.edit_input_url));
            final TextView pwdEdit = (TextView) layout.findViewById(R.id.edit_input_pwd);
            LinearLayout keyBoard = (LinearLayout) layout.findViewById(R.id.ll_keyboard);

            initKeyBoard(keyBoard,pwdEdit);

            String devId = Utils.getDevCode();

            edit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (!TextUtils.isEmpty(title) && devId.equals(title)) {
                        txt_close.setVisibility(View.VISIBLE);
                        pwdEdit.setHint("请输入管理密码");
                        dialog.initTimer();
                    }
                }
            });


            if (!TextUtils.isEmpty(title) & devId.equals(title)) {
//                edit.setInputType(InputType.TYPE_CLASS_TEXT  | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//                edit.clearFocus();
                pwdEdit.setHint("请输入管理密码");
                keyBoard.setVisibility(View.VISIBLE);
                edit.setVisibility(View.GONE);
                pwdEdit.setVisibility(View.VISIBLE);
            }

            if (!TextUtils.isEmpty(title) & "请输入服务器地址".equals(title)) {
                keyBoard.setVisibility(View.GONE);
                pwdEdit.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(url)) {

                    edit.setText(url);
                    imageView.setVisibility(View.GONE);
                }
            }

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnCloseListener.onClick(dialog,
                            DialogInterface.BUTTON_NEUTRAL);
                }
            });
            // set the confirm button
            if (positiveButtonText != null) {
                ((Button) layout.findViewById(R.id.positiveButton))
                        .setText(positiveButtonText);
                if (positiveButtonClickListener != null) {
                    ((Button) layout.findViewById(R.id.positiveButton))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {

                                    String msg = edit.getText().toString();
                                    String pwd = pwdEdit.getText().toString();
                                    if (!TextUtils.isEmpty(title) && devId.equals(title)) {
                                        setUrl(pwd);
                                    }

                                    if (!TextUtils.isEmpty(title) && "请输入服务器地址".equals(title)) {
                                        setUrl(msg);
                                    }

                                    positiveButtonClickListener.onClick(dialog,
                                            DialogInterface.BUTTON_POSITIVE);
                                }
                            });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                layout.findViewById(R.id.positiveButton).setVisibility(
                        View.GONE);
            }
            // set the cancel button
            if (negativeButtonText != null) {
                ((Button) layout.findViewById(R.id.negativeButton))
                        .setText(negativeButtonText);
                if (negativeButtonClickListener != null) {
                    ((Button) layout.findViewById(R.id.negativeButton))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    negativeButtonClickListener.onClick(dialog,
                                            DialogInterface.BUTTON_NEGATIVE);
                                }
                            });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                layout.findViewById(R.id.negativeButton).setVisibility(
                        View.GONE);
            }

            dialog.setContentView(layout);
            dialog.setCancelable(false);
            return dialog;
        }
    }

    private void initTimer() {
        Log.d("InternetDialog","15秒计时开始");
        resetTimer();
        fifteemTimer = new Timer(true);
        fifteemTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(FIFTEEM);
            }
        },0,1 * 1000);
    }

    private void resetTimer() {
        if (fifteemTimer != null) {
            fifteemTimer.cancel();
            FIFTEEM_SECOND = SECOND;
        }
    }

    private static void initKeyBoard(LinearLayout keyBoardLayout, final TextView pwdEdit) {
        pwdEdit.setText("");

        Button btn_one = (Button) keyBoardLayout.findViewById(R.id.btn_one);
        Button btn_two = (Button) keyBoardLayout.findViewById(R.id.btn_two);
        Button btn_three = (Button) keyBoardLayout.findViewById(R.id.btn_three);
        Button btn_four = (Button) keyBoardLayout.findViewById(R.id.btn_four);
        Button btn_five = (Button) keyBoardLayout.findViewById(R.id.btn_five);
        Button btn_six = (Button) keyBoardLayout.findViewById(R.id.btn_six);
        Button btn_seven = (Button) keyBoardLayout.findViewById(R.id.btn_seven);
        Button btn_eight = (Button) keyBoardLayout.findViewById(R.id.btn_eight);
        Button btn_nine = (Button) keyBoardLayout.findViewById(R.id.btn_nine);
        Button btn_zero = (Button) keyBoardLayout.findViewById(R.id.btn_zero);
        Button btn_del = (Button) keyBoardLayout.findViewById(R.id.btn_del);

        btn_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("1");
            }
        });

        btn_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("2");
            }
        });
        btn_three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("3");
            }
        });
        btn_four.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("4");
            }
        });
        btn_five.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("5");
            }
        });
        btn_six.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("6");
            }
        });
        btn_seven.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("7");
            }
        });
        btn_eight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("8");
            }
        });
        btn_nine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("9");
            }
        });
        btn_zero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdEdit.append("0");
            }
        });

        btn_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String num = pwdEdit.getText().toString();
                if (!TextUtils.isEmpty(num)) {
                    num = num.substring(0,num.length()-1);
                    pwdEdit.setText(num);
                }
            }
        });

    }

    @Override
    public void dismiss() {

        super.dismiss();
        resetTimer();
    }
}
